package cn.edu.ncepu;

/**
 * 复数类，包含实部和虚部，以及自定义乘法方法
 */
class Complex {
    // 实部和虚部（使用double类型保证精度）
    private final double real;
    private final double imag;

    // 构造方法
    public Complex(double real, double imag) {
        this.real = real;
        this.imag = imag;
    }

    // 获取实部
    public double getReal() {
        return real;
    }

    // 获取虚部
    public double getImag() {
        return imag;
    }

    // 自定义复数乘法（复刻Python的mul逻辑）
    public Complex mul(Complex other) {
        double a = this.real;
        double b = this.imag;
        double c = other.real;
        double d = other.imag;

        double m1 = (a + b) * (c - d);
        double m2 = b * c;
        double m3 = a * d;

        // 计算结果的实部和虚部
        double resultReal = m1 - m2 + m3;
        double resultImag = m2 + m3;

        return new Complex(resultReal, resultImag);
    }

    // 重写toString方法，方便打印输出（格式：a + bj）
    @Override
    public String toString() {
        if (imag >= 0) {
            return real + " + " + imag + "j";
        } else {
            return real + " - " + Math.abs(imag) + "j";
        }
    }
}

// 测试类
public class ComplexMultiplication {
    public static void main(String[] args) {
        // 测试用例：(1 + 3j) * (2 + 5j)
        Complex x = new Complex(1, 3);
        Complex y = new Complex(2, 5);
        Complex result = x.mul(y);

        // 打印结果
        System.out.println("(" + x + ") * (" + y + ") = " + result);

        // 验证：标准复数乘法 (a+bj)(c+dj) = (ac-bd) + (ad+bc)j
        // 手动计算：(1*2 - 3*5) + (1*5 + 3*2)j = (2-15)+(5+6)j = -13 + 11j
        // 对比自定义方法的结果是否一致
        double standardReal = x.getReal() * y.getReal() - x.getImag() * y.getImag();
        double standardImag = x.getReal() * y.getImag() + x.getImag() * y.getReal();
        Complex standardResult = new Complex(standardReal, standardImag);
        System.out.println("标准复数乘法结果：" + standardResult);
        System.out.println("自定义乘法与标准乘法结果是否一致：" +
                (Math.abs(result.getReal() - standardReal) < 1e-9
                        && Math.abs(result.getImag() - standardImag) < 1e-9));
    }
}